package com.gigi.datageniebackendmaster.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Excel 处理工具类
 *
 * @author Gigi
 * @date 2024/7/21 13:14
 */
public class ExcelUtil {

    /**
     * Excel 转 Csv
     *
     * @param file
     * @return
     */
    public static String excelToCsv(MultipartFile file) throws IOException {

        // easyexcel 读取 excel
        List<Map<Integer, String>> list = EasyExcel.read(file.getInputStream())
                .excelType(ExcelTypeEnum.XLSX)
                .sheet()
                .headRowNumber(0)
                .doReadSync();

        if (CollUtil.isEmpty(list)) {
            return StrUtil.EMPTY;
        }

        // 转换为 csv
        StringBuilder stringBuilder = new StringBuilder();

        // 读取表头
        LinkedHashMap<Integer, String> headerMap = (LinkedHashMap) list.get(0);
        List<String> headerList = headerMap.values().stream().filter(Objects::nonNull).collect(Collectors.toList());
        stringBuilder.append(StrUtil.join(StrUtil.COMMA, headerList)).append(StrUtil.LF);

        // 读取数据
        for (int i = 1; i < list.size(); i++) {
            LinkedHashMap<Integer, String> dataMap = (LinkedHashMap) list.get(i);
            List<String> dataList =
                    dataMap.values().stream().filter(e -> CollUtil.isNotEmpty(Collections.singleton(e))).collect(Collectors.toList());
            stringBuilder.append(StrUtil.join(StrUtil.COMMA, dataList)).append(StrUtil.LF);
        }
        return stringBuilder.toString();
    }

}
